<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/19 0019
 * Time: 17:57
 */

namespace app\api\controller;

use app\api\library\WechatHandle;
use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Config;
use think\Db;
use think\Request;
use app\admin\model\Outsideschool as outside;
use app\admin\model\ReceptionUnit;

class Outsideschool extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $model = null;
    const KEY = '4wuKXx7R';
    const EXPIRE = 86400; // 24小时
    
    public function _initialize()
    {
        parent::_initialize();

        $this->model = new outside();

        
    }
    public function index(){
        //鉴权
        if (!$this->request->isPost()) {
            $this->error('非法请求', [],2);
        }

        $param = $this->request->post();

        if (!isset($param['_time']) || !isset($param['_key']) || !isset($param['nickname']) || !isset($param['tel']) || !isset($param['card_id']) ) {
            $this->error('参数不完整', [],3);
        }
        if($param['_key'] != self::KEY){
            $this->error('不合理的请求', [],2);
        }
        $times = $this->timediff($param['_time'],time());
        if($times['min']>5 || $times['min']<0){
            $this->error('请求超时', [],4);
        }
        // if (time() - $param['_time'] > self::EXPIRE || time() - $param['_time'] < (0 - self::EXPIRE)) {
        //     $this->error('请求超时', [],4);
        // }

        if(!$this->is_idcard(trim($param['card_id']))){
            $this->error('请输入合理的身份证', [],5);
        }

        unset($param['_key']);
        unset($param['_time']);

        $res = $this->model->allowField(true)->save($param);
        if($res){
            // $info = ReceptionUnit::get($param['reception_id']);
            // if($info -> mobile){
            //     $msg = urlencode(mb_convert_encoding("您有一份{$param['applier_name']}老师提交的校外人员入校预约申请需要审批。",'gb2312'));
            //     $url = 'http://114.255.71.158:8061/?username=qdnydx&password=QAUnmc123&message='.$msg.'&phone='.($info -> mobile).'&epid=122985&linkid=&subcode=';
            //     geturl($url);//发送短信
            // }
            $this->success('预约成功');
        }else{
            $this->error('预约失败');
        }
    }

    public function unit(){
        $where['id'] = ['<>',1];
        $reception_unit = ReceptionUnit::where($where)->where('sort>0')->order('sort')->field("name,id")->select();
        $this->error('请求成功',$reception_unit);
    }

    /**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     */
    public function request_post($url = '', $post_data = array()) {
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $o = "";
        foreach ( $post_data as $k => $v ) 
        { 
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);

        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }


    public function friend(){
        $list = Db::query('select APPLIER_ID from qa_school_friend  group by APPLIER_ID having count(*)>=2');
        foreach($list as $key => $val) {
            // echo $value['APPLIER_ID']."<br/>";
            $info = Db::name('school_friend')->where(['APPLIER_ID'=>$val['APPLIER_ID']])->order('id')->find();
            Db::name('school_friend')->where(['APPLIER_ID'=>$val['APPLIER_ID']])->where('id!='.$info['id'])->delete();
        }
    }


    /**
     * 
     * [_Schoolfriend description]
     * @return [type] [description]
     */
    protected function _Schoolfriend()
    {
        // $Oracle_conn = @oci_connect('googosoft_zc', 'googosoft_zc', "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.8.36.122)(PORT=1521))(CONNECT_DATA=(SID=shitan)))", "UTF8");
        $dbconn=oci_connect('user_xyb_xy','QauXybXy12#$',"(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.8.16.80)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=icdc)))","UTF8");
        if (!$dbconn) {
           echo '连接失败';
           die();
        }
        $APPLIER_ID = '195241';
        $sql="select * from icdc_ods.view_xyb_xy_wlryrxxx where APPLIER_ID=".$APPLIER_ID;
        $data = $this -> exec($dbconn,$sql);
        echo "<pre>";
        var_dump($data);
        echo count($data);


        // $query = "insert into icdc_ods.view_xyb_xy_wlryrxxx(APPLIER_ID,APPLIER_NAME,RECEPTION_ID,RECEPTION_NAME,SFZJH,GZDW,SJHM,ZY,SZBJ) values ";
        // $values = "('910218','贾小兵','149','动物医学院','622428199102141418','工作单位','18661473759','计算机科学与技术','计算机0308')";
        // $query .= $values;
        // // p($query,false);计算机

        // // p($Oracle_conn, false);
        // $stid = oci_parse($dbconn, $query);
        // $r = oci_execute($stid);
        // echo "<pre>";
        // var_dump($r);
        // exit();


    }

     protected function exec($dbconn = null, $sql = ''){
        $stid = oci_parse($dbconn, $sql); // 配置SQL语句，准备执行
        if (!$stid) {
            $e = oci_error($dbconn);
            print htmlentities($e['message']);
            exit;
        }
        $r = oci_execute($stid, OCI_DEFAULT); // 执行SQL。OCI_DEFAULT表示不要自动commit
        if(!$r) {
            $e = oci_error($stid);
            echo htmlentities($e['message']);
            exit;
        }


        oci_fetch_all($stid,$data);

        $insertData = [];
        foreach ($data as $k => $v){
            foreach ($v as $kk => $vv){
                $insertData[$kk][$k] = $vv;
            }
        }
        return $insertData;
    }



    /**
     * 校友接口提交校外人员申请接口
     * [alumnus description]
     * @return [type] [description]
     */
    public function alumnus(){

        $res = $this->_Schoolfriend();
        echo "<pre>";
        var_dump($res);
        exit();
        // $list = Db::connect('db2')->table('icdc_ods.view_xyb_xy_wlryrxxx')->count();
        // halt($list);
        // exit();
        set_time_limit(300);
        $url="https://ds.qau.edu.cn/dataservices/oauth/token";
        $post_data['client_id']       = '23d6b223550a8cd4a1f22384881e1710';
        $post_data['client_secret']      = 'e007b88a32b2773eef97b35a9195e6cc';
        $res = $this->request_post($url, $post_data);   
        $result = json_decode($res,true);
        if(!empty($result['access_token'])){
            $access_token = $result['access_token'];
            $data_url="https://ds.qau.edu.cn/dataservices/services/XY_WLRYRXXX.svc/VIEW_XYB_XY_WLRYRXXX?access_token=".$access_token;

            // echo $data_url."<br/>";
            $data=  file_get_contents($data_url);
            echo $data;exit();
            $list =  json_decode($data,true);

            echo "<pre>";
            var_dump($list);
            echo count($list['value']);
            exit();
            if(!empty($list['value'])){
                foreach ($list['value'] as $k => $v) {
                    // echo $v['APPLIER_NAME']."####".$v['APPLIER_ID']."<br/>";
                    $info = Db::name('school_friend')->where(['APPLIER_ID'=>$v['APPLIER_ID'],'APPLIER_NAME'=>$v['APPLIER_NAME']])->find();
                    if(empty($info)){
                        $add = [
                            'APPLIER_ID'=>$v['APPLIER_ID'],
                            'APPLIER_NAME'=>$v['APPLIER_NAME'],
                            'RECEPTION_ID'=>$v['RECEPTION_ID'],
                            'RECEPTION_NAME'=>$v['RECEPTION_NAME'],
                            'SFZJH'=>$v['SFZJH'],
                            'GZDW'=>$v['GZDW'],
                            'SJHM'=>$v['SJHM'],
                            'ZY'=>$v['ZY'],
                            'SZBJ'=>$v['SZBJ'],
                            'create_time'=>time(),
                            'update_time'=>time(),
                        ];
                        Db::name('school_friend')->insert($add);
                    }else{
                        continue;
                    }
                }
            }
            // echo count($list['value'])."<br/>";
        }
        exit('完成');

        // // $body = array("client_id"=>"23d6b223550a8cd4a1f22384881e1710", "client_secret"=>"e007b88a32b2773eef97b35a9195e6cc");
        // // $header = array("Content-Type:multipart/x-www-form-urlencoded", "token:test", "client:h5");
        // // $result = $this->curlPost($url, $body, 5, $header, 'json');
        // // halt($result);
        // // exit();

        // //鉴权
        // if (!$this->request->isPost()) {
        //     $this->error('非法请求', [],2);
        // }

        // $param = $this->request->post();

        // if (!isset($param['_time']) || !isset($param['_key']) || !isset($param['nickname']) || !isset($param['tel']) || !isset($param['card_id']) ) {
        //     $this->error('参数不完整', [],3);
        // }
        // if($param['_key'] != self::KEY){
        //     $this->error('不合理的请求', [],2);
        // }
        // $times = $this->timediff($param['_time'],time());
        // if($times['min']>5 || $times['min']<0){
        //     $this->error('请求超时', [],4);
        // }

        // if(!$this->is_idcard(trim($param['card_id']))){
        //     $this->error('请输入合理的身份证', [],5);
        // }

        // unset($param['_key']);
        // unset($param['_time']);
        // $param['applier_id'] = '200401160';
        // $param['applier_name'] = '于宁';
        // $param['reception_id'] = 45;
        // $param['reception_name'] = '艺术学院';
        // $res = $this->model->allowField(true)->save($param);
        // if($res){
        //     // $info = ReceptionUnit::get($param['reception_id']);
        //     // if($info -> mobile){
        //     //     $msg = urlencode(mb_convert_encoding("您有一份{$param['applier_name']}老师提交的校外人员入校预约申请需要审批。",'gb2312'));
        //     //     $url = 'http://114.255.71.158:8061/?username=qdnydx&password=QAUnmc123&message='.$msg.'&phone='.($info -> mobile).'&epid=122985&linkid=&subcode=';
        //     //     geturl($url);//发送短信
        //     // }
        
        //     // 教工号或者手机号
        //     // send_wechat_work_msg([200101051], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$params['applier_name'].'提交的入校预约申请需要审批。</a>');
        //     $this->success('预约成功，待接待单位领导审批！');
        // }else{
        //     $this->error('预约失败');
        // }


        
    }

    public function timediff($begin_time,$end_time)
    {
        if($begin_time < $end_time){
            $starttime = $begin_time;
            $endtime = $end_time;
        }else{
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        //计算天数
        $timediff = $endtime-$starttime;
        $days = intval($timediff/86400);
        //计算小时数
        $remain = $timediff%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);
        //计算秒数
        $secs = $remain%60;
        $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
        return $res;
    }

    /********************php验证身份证号码是否正确函数*********************/
    function is_idcard( $id )
    {
      $id = strtoupper($id);
      $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
      $arr_split = array();
      if(!preg_match($regx, $id))
      {
        return FALSE;
      }
      if(15==strlen($id)) //检查15位
      {
        $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
      
        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确
        $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
        if(!strtotime($dtm_birth))
        {
          return FALSE;
        } else {
          return TRUE;
        }
      }
      else      //检查18位
      {
        $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
        if(!strtotime($dtm_birth)) //检查生日日期是否正确
        {
          return FALSE;
        }
        else
        {
          //检验18位身份证的校验码是否正确。
          //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
          $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
          $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
          $sign = 0;
          for ( $i = 0; $i < 17; $i++ )
          {
            $b = (int) $id{$i};
            $w = $arr_int[$i];
            $sign += $b * $w;
          }
          $n = $sign % 11;
          $val_num = $arr_ch[$n];
          if ($val_num != substr($id,17, 1))
          {
            return FALSE;
          } //phpfensi.com
          else
          {
            return TRUE;
          }
        }
      }
      
    }

    


    public function ispost(){
        $push_api_url = "http://yq.work.com/api/outsideschool/alumnus";
        $post_data = [
            '_time'=>time(),
            '_key'=>'4wuKXx7R',
            "tel"=>"13899999999", 
            "nickname"=>"Nick",
            'card_id'=>'622428199102141418',
            'work_unit'=>'xxxx公司',
            'memo'=>'合作交流',
            'admission_starttime'=>'20230222',
            'admission_endtime'=>'20230223',
            'car_number'=>'鲁B0832N'
        ];
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $push_api_url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
        $return = curl_exec ( $ch );
        curl_close ( $ch );
        var_dump($return);
    }




}